using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using MVBuddy.Common.Helpers;
using MVBuddy.Common.Model;
using MVBuddy.Messages;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Media.Imaging;

namespace MVBuddy.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        private string username;
        public string Username
        {
            get
            {
                return this.username;
            }
            set
            {
                if (this.username != value)
                {
                    this.username = value;
                    RaisePropertyChanged(() => this.Username);
                }
            }
        }

        private string password;
        public string Password
        {
            get
            {
                return this.password;
            }
            set
            {
                if (this.password != value)
                {
                    this.password = value;
                    RaisePropertyChanged(() => this.Password);
                }
            }
        }

        private UserData userData;
        public UserData UserData
        {
            get
            {
                return this.userData;
            }
            set
            {
                if (this.userData != value)
                {
                    this.userData = value;
                    RaisePropertyChanged(() => this.UserData);
                }
            }
        }

        private bool saveLogin;
        public bool SaveLogin
        {
            get
            {
                return this.saveLogin;
            }
            set
            {
                if (this.saveLogin != value)
                {
                    this.saveLogin = value;
                    RaisePropertyChanged(() => this.SaveLogin);
                }
            }
        }

        private RelayCommand navigateNotificationsCommand;
        public RelayCommand NavigateNotificationsCommand
        {
            get
            {
                if (this.navigateNotificationsCommand == null)
                {
                    this.navigateNotificationsCommand = new RelayCommand(() =>
                        {
                            WebBrowserTask webTask = new WebBrowserTask();
                            webTask.Uri = new Uri("http://m.mediavida.com/notificaciones");
                            webTask.Show();
                        });
                }

                return this.navigateNotificationsCommand;
            }
        }

        private RelayCommand navigateFavoritesCommand;
        public RelayCommand NavigateFavoritesCommand
        {
            get
            {
                if (this.navigateFavoritesCommand == null)
                {
                    this.navigateFavoritesCommand = new RelayCommand(() =>
                        {
                            WebBrowserTask webTask = new WebBrowserTask();
                            webTask.Uri = new Uri("http://m.mediavida.com/foro/favoritos");
                            webTask.Show();
                        });
                }

                return this.navigateFavoritesCommand;
            }
        }

        private RelayCommand navigateMessagesCommand;
        public RelayCommand NavigateMessagesCommand
        {
            get
            {
                if (this.navigateMessagesCommand == null)
                {
                    this.navigateMessagesCommand = new RelayCommand(() =>
                        {
                            WebBrowserTask webTask = new WebBrowserTask();
                            webTask.Uri = new Uri("http://m.mediavida.com/mensajes");
                            webTask.Show();
                        });
                }

                return this.navigateMessagesCommand;
            }
        }

        public MainViewModel()
        {
            string storedUsername = StorageManager.LoadAppSetting("Username") as string;
            string storedPassword = StorageManager.LoadAppSetting("Password") as string;

            Messenger.Default.Register<RequestLoginMessage>(this, RequestLoginMessageReceived);
            Messenger.Default.Register<RequestPinTileMessage>(this, RequestPinTileMessageReceived);

            this.Username = storedUsername == null ? string.Empty : storedUsername;
            this.Password = storedPassword == null ? string.Empty : storedPassword;

            if (this.Username != string.Empty && this.Password != string.Empty)
            {
                this.SaveLogin = true;
            }
            else
            {
                this.SaveLogin = false;
            }
        }

        private void RequestLoginMessageReceived(RequestLoginMessage message)
        {
            HtmlRequest loginRequest = new HtmlRequest(new Uri("http://m.mediavida.com/login.php"), "POST", "application/x-www-form-urlencoded", new System.Collections.Generic.Dictionary<string, string>()
                {
                    { "name", this.Username },
                    { "password", this.Password },
                });

            loginRequest.HtmlRequestCompleted += loginRequest_HtmlRequestCompleted;
            loginRequest.DoRequest();
        }

        private void RequestPinTileMessageReceived(RequestPinTileMessage message)
        {
            if (ShellTile.ActiveTiles.ToList().Count < 2)
            {
                ShellTile.Create(new Uri("/View/MainPage.xaml", UriKind.Relative), new StandardTileData()
                {
                    BackBackgroundImage = null,
                    BackContent = string.Empty,
                    BackgroundImage = new Uri("Background.png", UriKind.Relative),
                    BackTitle = string.Empty,
                    Title = "MV Buddy",
                });
            }
        }

        private void loginRequest_HtmlRequestCompleted(object sender, HtmlRequestCompletedEventArgs e)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.UserData = UserDataExtractor.Extract(e.Result);

                    if (this.UserData.Logged)
                    {
                        if (this.SaveLogin == true)
                        {
                            StorageManager.SaveAppSetting("Username", this.Username);
                            StorageManager.SaveAppSetting("Password", this.Password);

                            RegisterTaskAgent();
                        }

                        if (ShellTile.ActiveTiles.ToList().Count > 1)
                        {
                            ShellTile tile = ShellTile.ActiveTiles.ElementAtOrDefault(1);
                            string tilePath = "/Shared/ShellContent/TileBackBackground.jpg";

                            WriteableBitmap backBitmap = UserDataExtractor.RenderUserDataForBackgroundTile(this.UserData);
                            StorageManager.SaveShellBitmapAsJpeg(tilePath, backBitmap);

                            tile.Update(new StandardTileData()
                            {
                                BackTitle = string.Empty,
                                Count = UserData.NotificationCount + UserData.FavoriteCount + UserData.MessageCount,
                                BackContent = string.Empty,
                                BackBackgroundImage = new Uri("isostore:" + tilePath, UriKind.Absolute),
                            });
                        }

                        Messenger.Default.Send(new LoginSuccessfulMessage());
                    }
                    else
                    {
                        Messenger.Default.Send(new LoginFailedMessage());
                    }
                });
        }

        private void RegisterTaskAgent()
        {
            PeriodicTask periodicTask = new PeriodicTask("MVBuddy.TaskAgent");
            periodicTask.Description = "Actualiza el tile con los datos de notificaciones.";
            periodicTask.ExpirationTime = DateTime.Now + TimeSpan.FromDays(7);

            try
            {
                if (ScheduledActionService.Find(periodicTask.Name) != null)
                {
                    ScheduledActionService.Remove(periodicTask.Name);
                }
                ScheduledActionService.Add(periodicTask);
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("exists already"))
                {
                    MessageBox.Show("The background agent is already running.");
                }
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background processes for this application have been prohibited.");
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type has already been added."))
                {
                    MessageBox.Show("Background agent exceeded hardware limitations.");
                }
            }
            catch (SchedulerServiceException)
            {
            }
        }
    }
}